<template>
    <van-sticky>
        <van-nav-bar left-arrow @click-left="onClickNavLeft" title="个人信息" />
    </van-sticky>
    <div id="profile">
        <van-skeleton :row="15" :loading="isLoading">
            <van-cell-group inset title="个人信息">

                <van-cell center clickable @click="onClickAvatar" class="avatar-uploader" title="头像设置">
                    <template #value>
                        <van-uploader v-model="fileList" multiple :max-count="1" ref="avatarUploader">
                            <van-image
                            round
                            fit="cover"
                            src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
                            width="60"
                            height="60"
                            />
                        </van-uploader>
                    </template>
                </van-cell>

                <van-cell clickable title="UID" :value="userProfile.id" @click="clickTest"/>

                <van-cell clickable title="昵称" :value="userProfile.nickname" @click="nameClick"/>
                <v-dialog v-model:show="showChangeName" title="更改昵称" close-on-click-overlay show-cancel-button @confirm="changeName" :before-close="validateName">
                    <van-field
                    v-model="changeNameBind"
                    label="新用户名"
                    maxlength="16"
                    show-word-limit
                    >
                    </van-field>
                </v-dialog>

                <van-cell clickable title="性别" :value="gender" @click="genderClick"/>
                <van-popup :show="showGenderPopup" close-on-click-overlay @close="closeOverlay" round position="bottom" :style="{ height: '30%' }">
                    <van-picker
                    title="更改性别"
                    :columns="genders"
                    @confirm="onGenderConfirm"
                    @cancel="onGenderCancel"
                    :default-index="userProfile.gender-1"
                    />
                </van-popup>

                <van-cell clickable title="年龄" :value="userProfile.age" @click="ageClick"/>
                <van-popup :show="showAgePopup" close-on-click-overlay @close="closeOverlay" round position="bottom" :style="{ height: '30%' }">
                    <van-picker
                    title="更改年龄"
                    :columns="ages"
                    @confirm="onAgeConfirm"
                    @cancel="onAgeCancel"
                    :default-index="userProfile.age-1"
                    />
                </van-popup>

                <van-cell class="motto-content" clickable title="个性签名" :value="userProfile.motto" @click="mottoClick"/>
                <van-popup :show="showMottoPopup" close-on-click-overlay position="bottom" :style="{ height: '40%' }" @close="changeMotto">
                    <van-field
                        v-model="changeMottoBind"
                        autosize
                        label="修改个性签名"
                        type="textarea"
                        maxlength="200"
                        placeholder="请输入个性签名"
                        show-word-limit
                    />
                </van-popup>
            </van-cell-group>
        </van-skeleton>
    </div>
</template>


<script>
import {Gender} from '@/utils/api/me'
import {storeUserProfile,retrieveUserProfile} from '@/utils/storage'
import {getSelfProfile,updateSelfProfile} from '@/utils/api/me'
import { Dialog } from 'vant'
import 'vant/es/dialog/style';

const ages = []
for (let age = 1; age <= 149; age++) {
    ages.push(age)
}
const genders = ["不适用","男","女","非二元"]

export default {
    name: 'ProfileSettingView',
    components: {
        'v-dialog': Dialog.Component, //vant3 bug
    },
    data() {
        return {
            isLoading: true,
            showAgePopup: false,
            showGenderPopup: false,
            showChangeName: false,
            changeNameBind: "",
            showMottoPopup: false,
            changeMottoBind: "",
            fileList: [],
        }
    },
    computed: {
        userProfile(){
            return this.$store.state.userProfile
        },
        gender(){
            switch (this.userProfile.gender) {
                case Gender.NA:
                    return "不适用";
                case Gender.MALE:
                    return "男";
                case Gender.FEMALE:
                    return "女";
                case Gender.NON_BINARY:
                    return "非二元";
                default:
                    return "无效数据";
            }
        },
        ages(){
            return ages
        },
        genders(){
            return genders
        }
    },
    methods: {
        //假定在此页,用户一定已经登陆了
        loadLocalProfile(){
            const profile = retrieveUserProfile()
            this.$store.commit('setUserProfile',profile)
        },
        async loadNetworkProfile(){
            const profileResult = await getSelfProfile()
            //更新localStorage中的profile值
            storeUserProfile(profileResult.data)
            this.$store.commit('setUserProfile',profileResult.data)
        },
        clickTest(){
            this.$toast.success("点击成功")
        },
        ageClick(){
            this.showAgePopup = true
        },
        onAgeCancel(){
            this.showAgePopup = false
        },
        async updateProfile(profile){
            this.$store.commit('setUserProfile',profile)
            storeUserProfile(profile)
            await updateSelfProfile(profile)
            this.$toast.success("已保存更改")
        },
        async onAgeConfirm(value){
            this.showAgePopup = false
            //更新vuex,localStorage,并更新至服务器
            const profile = this.userProfile
            profile.age = value
            this.updateProfile(profile)
        },
        genderClick() {
            this.showGenderPopup = true
        },
        onGenderCancel(){
            this.showGenderPopup = false
        },
        async onGenderConfirm(value,index){
            this.showGenderPopup = false
            //更新vuex,localStorage,并更新至服务器
            const profile = this.userProfile
            profile.gender = index+1
            this.updateProfile(profile)
        },
        nameClick(){
            this.changeNameBind = this.userProfile.nickname
            this.showChangeName = true
        },
        async changeName(){
            const profile = this.userProfile
            profile.nickname = this.changeNameBind
            this.updateProfile(profile)
        },
        async validateName(action){
            if (action === "cancel"){
                return true
            }
            //校验 1.不能是空名 2.不能全是空白
            if (this.changeNameBind.trim() === "") {
                this.$toast.fail("昵称不能为空")
                return false
            }
            return true
        },
        mottoClick(){
            this.changeMottoBind = this.userProfile.motto
            this.showMottoPopup = true
            console.log(this.$store.state.user)
        },
        async changeMotto(){
            this.showMottoPopup = false
            const profile = this.userProfile
            profile.motto = this.changeMottoBind
            this.updateProfile(profile)
        },
        closeOverlay(){
            this.showAgePopup = false
            this.showGenderPopup = false
        },
        onClickNavLeft(){
            this.$router.back()
        },
        onClickAvatar() {
            this.$refs.avatarUploader.chooseFile()
        }
    },
    mounted(){
        //切换到该页面时更新数据
        this.loadLocalProfile()
        this.loadNetworkProfile().then(()=>{this.isLoading=false})
    }
}
</script>


<style lang="scss" scoped>
#profile {
    margin: 0;
    overflow-x: auto;
    color: #323233;
    font-size: 16px;
    font-family: Open Sans,-apple-system,BlinkMacSystemFont,Helvetica Neue,Helvetica,Segoe UI,Arial,Roboto,PingFang SC,miui,Hiragino Sans GB,Microsoft Yahei,sans-serif;
    background-color: #f7f8fa;
    -webkit-font-smoothing: antialiased;
    text-align: start;
}

.motto-content {
    :deep(.van-cell__value) {
        min-width: 80%;
        text-align: left;
    }
}

.avatar-uploader {
    padding-top: 0px;
    padding-bottom: 0px;
}
</style>